﻿using System;
using System.Web;
using System.Web.Mvc;
using SlamCms.Common;
using SlamCms.Configuration;
using SlamCms.Data;

namespace SlamCms.Tracking
{
	public enum TrackingBehavior
	{
		NoTrack,
		Track
	}

	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
	public class TrackingAttribute : ActionFilterAttribute
	{
		static TrackingAttribute()
		{
			TrackingEnabled = ConfigurationHelpers.GetEnvironmentSetting(Constants.Settings.TrackingEnabled, true);
			TrackingChildActionsEnabled = ConfigurationHelpers.GetEnvironmentSetting(Constants.Settings.TrackingChildActionsEnabled, false);
			TrackingAjaxRequestsEnabled = ConfigurationHelpers.GetEnvironmentSetting(Constants.Settings.TrackingAjaxRequestsEnabled, false);
		}

		public static bool TrackingEnabled { get; set; }
		public static bool TrackingChildActionsEnabled { get; set; }
		public static bool TrackingAjaxRequestsEnabled { get; set; }
		public static Func<HttpContextBase, bool> OnPageTracking { get; set; }

		public TrackingAttribute() : this(TrackingBehavior.Track)
		{
		}

		public TrackingAttribute(TrackingBehavior trackingBehavior)
		{
			TrackingBehavior = trackingBehavior;
		}

		public TrackingBehavior TrackingBehavior { get; set; }

		public override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			if (!TrackingEnabled)
				return;

			// no tracking
			if (TrackingBehavior == TrackingBehavior.NoTrack)
				return;

			// ignore child actions
			if (!TrackingChildActionsEnabled && filterContext.IsChildAction)
				return;

			// ignore crawlers
			if ((filterContext.HttpContext.Request.UserAgent ?? string.Empty).In("crawler", "Googlebot", "Google"))
				return;

			// ignore ajax requests
			if (!TrackingAjaxRequestsEnabled && filterContext.HttpContext.Request.IsAjaxRequest())
				return;

			if (OnPageTracking != null && !OnPageTracking(filterContext.HttpContext))
				return;

			var trackingService = DependencyResolver.Current.GetService<ITrackingService>();
			
			trackingService.TrackCurrentPage();
		}
	}
}
